<template>
  <view v-show="curPage === 'form'">
    <slot name="navbar"></slot>
    <view class="flex-col-hcenter">
      <view class="card">
        <!-- name -->
        <view class="item-box split-line">
          <text class="talj" style="font-size: 32rpx">姓名</text>
          <input
            :value="name"
            type="text"
            placeholder="请填写姓名"
            placeholder-style="color: #666;text-align:right"
            @input="onChineseInput"
            maxlength="6"
          />
        </view>
        <!-- phone -->
        <view class="item-box split-line">
          <text class="talj" style="font-size: 32rpx">电话</text>
          <input
            :value="phone"
            type="number"
            placeholder="请填写联系电话"
            placeholder-style="color: #666;text-align:right"
            maxlength="11"
            @input="onNumberInput"
          />
        </view>
        <!-- location -->
        <view class="item-box split-line">
          <text class="talj" style="font-size: 32rpx">加注地址</text>
          <view class="pick-block" @click="openMap">
            <view class="flex-jcfe">
              <text>{{ addrLocation === '' ? '请选择加注地址' : addrLocation }}</text>
            </view>
            <view>
              <uni-icons type="right" size="20"></uni-icons>
            </view>
          </view>
        </view>
        <!-- address -->
        <view class="item-addr-box">
          <textarea
            v-model="address"
            placeholder="请填写详细地址"
            placeholder-style="color:#666"
            auto-height
            style="width: 100%"
          ></textarea>
        </view>
      </view>
      <slot></slot>
    </view>
  </view>
  <view v-if="curPage === 'map'"><web-view :src="mapURI"></web-view></view>
</template>

<script setup lang="ts">
import { integralocation } from '@/gql/user';
import { useAddressStore } from '@/stores/address';
import { getDriverID } from '@/stores/driverID';
import { navBack } from '@/utils/navigator';
import { errorToast, showLoading, showToast } from '@/utils/prompt';
import { onLoad } from '@dcloudio/uni-app';
import { toPublish } from '@mqtt';
import { nextTick, Ref, ref } from 'vue';
// #ifdef H5
import { defaultFail, getLocation } from '@/utils/wechat.jssdk';
// #endif

const props = defineProps({
  type: {
    type: String,
    required: true,
  },
});

// static
const driver_id = getDriverID();
let id = null as number;
let is_default = '0';
let latitude: number = null;
let longitude: number = null;
const mapURI = ref('');
// data
const addressStore = useAddressStore();
const curPage: Ref<'form' | 'map'> = ref('form');
const name = ref('');
const phone = ref('');
const addrLocation = ref('');
const address = ref('');

onLoad((options) => {
  if (props.type === 'editor') {
    id = Number.parseInt(options.id);
    getEditorAddrInfo();
  }
});

function getEditorAddrInfo() {
  const payload = {
    query: integralocation,
    variables: { id, driver_id },
  };
  showLoading();
  toPublish(
    'ql/driver/address',
    payload,
    (obj: any) => {
      const addr = obj.data.address;
      name.value = addr.consignee;
      phone.value = addr.phone;
      addrLocation.value = addr.abbreviate;
      address.value = addr.address;
      latitude = addr.latitude;
      longitude = addr.longitude;
      is_default = addr.is_default;
    },
    () => {
      errorToast('获取地址信息失败');
      addressStore.getList();
      setTimeout(navBack, 1500);
    },
  );
}

// #ifdef H5
function chooseLocation() {
  mapURI.value = `https://apis.map.qq.com/tools/locpicker?coord=${latitude},${longitude}&search=1&type=1&key=URFBZ-F4TKI-SLPGX-57GMO-ZHYM6-BCFSL&referer=安蓝环保`;
  curPage.value = 'map';

  function msgListener(event) {
    // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
    const data = event.data;
    if (data && data.module == 'locationPicker') {
      //防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
      // location.value = `${data.poiaddress}-${data.poiname}`;
      addrLocation.value = data.poiaddress;
      curPage.value = 'form';
      window.removeEventListener('message', msgListener);
    }
  }
  window.addEventListener('message', msgListener, false);
}
// #endif

function openMap() {
  showLoading('加载中');
  // #ifdef H5
  function success(res: any) {
    uni.hideLoading();
    latitude = Number.parseFloat(res.latitude);
    longitude = Number.parseFloat(res.longitude);
    chooseLocation();
  }
  function fail() {
    // TODO
    showToast('请允许位置权限帮您准确定位');
    setTimeout(() => {
      uni.getLocation({
        type: 'gcj02',
        altitude: true,
        success(res) {
          uni.hideLoading();
          longitude = res.longitude;
          latitude = res.latitude;
          chooseLocation();
        },
      });
    }, 2000);
  }
  getLocation(success, defaultFail('getLocation', fail));
  // #endif

  // #ifndef H5
  uni.chooseLocation({
    success(res) {
      uni.hideLoading();
      addrLocation.value = res.address;
      latitude = res.latitude;
      longitude = res.longitude;
      curPage.value = 'form';
    },
    fail(res) {
      uni.hideLoading();
    },
  });
  // #endif
}

function onChineseInput(evt: any) {
  const { detail } = evt;
  const rule = /[^\u4E00-\u9FA5]/g; // 匹配非中文字符
  const value = detail.value.replace(rule, '');
  nextTick(() => {
    name.value = value;
  });
}

function onNumberInput(evt: any) {
  const { detail } = evt;
  const rule = /[^\d]/g;
  const value = detail.value.replace(rule, '');
  nextTick(() => {
    phone.value = value;
  });
}

function checkForm() {
  const isNotEmpty = name.value !== '' && phone.value !== '' && addrLocation.value !== '';
  if (!isNotEmpty) {
    showToast('请将信息填写完整');
    return false;
  }
  const isPhoneNumber = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/.test(phone.value);
  if (!isPhoneNumber) {
    showToast('请填写有效的手机号');
    return false;
  }
  return true;
}
function getAddressInfo() {
  const info = {
    consignee: name.value,
    phone: phone.value,
    abbreviate: addrLocation.value,
    address: address.value,
    latitude,
    longitude,
  };
  if (props.type === 'adder') {
    return info;
  } else {
    return {
      id,
      is_default,
      ...info,
    };
  }
}
defineExpose({
  checkForm,
  getAddressInfo,
});
</script>

<style scoped lang="less">
.card {
  margin-top: 15rpx;
  width: 96%;
  background: white;
  border-radius: 5px;
  box-shadow: 0rpx 0rpx 51rpx 0rpx rgba(179, 179, 179, 0.25);
}
.item-box {
  height: 120rpx;
  padding: 0 30rpx;
  font-size: 30rpx;
  color: #333;
  display: grid;
  grid-template-columns: 20% 75%;
  column-gap: 5%;
  align-items: center;

  input {
    text-align: right;
  }

  &.split-line {
    border-bottom: 2rpx solid rgba(238, 238, 238, 0.6);
  }

  .pick-block {
    color: #666;
    display: grid;
    grid-template-columns: 450rpx 20rpx;
    justify-content: end;
    align-items: center;
  }
}
.item-addr-box {
  box-sizing: border-box;
  min-height: 120rpx;
  padding: 30rpx;
  font-size: 32rpx;
  color: #333;
  display: grid;
  align-items: center;
}
</style>
